package com.xiaohudie.SSGworket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @Author xiao hu die
 * @Date 2022/3/27 18:55
 * @Version 1.0
 */
public class Tcptest03 {
    public static void main(String[] args) {
        Socket socket =null;
        OutputStream  outputStream =null;
        FileInputStream fileInputStream =null;
        try {
            InetAddress byName = InetAddress.getByName("127.0.0.1");
              socket =new Socket(byName,8899);
               outputStream = socket.getOutputStream();
               fileInputStream =new FileInputStream("D:\\java图片代码\\22.txt");
              byte[] bytes =new byte[1024*5];
              int len;
              while ((len =fileInputStream.read(bytes))!=-1){
                  outputStream.write(bytes,0,len);
              }
              /**关闭数据传输流，保证服务端得知数据已传输，不会阻塞*/
              socket.shutdownOutput();
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes1 =new byte[1024];
              int len1;
              while ((len1=inputStream.read(bytes1))!=-1){
                  byteArrayOutputStream.write(bytes1,0,len1);
              }
            System.out.println(byteArrayOutputStream.toString());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
